package com.hjj.interceptor;

import com.hjj.beans.User;
import com.hjj.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyLoginInterceptor implements HandlerInterceptor {
    @Autowired
    @Qualifier("userServicesFilterImp")
    UserServices userServices;


    // 请求之前
    // 返回true：可以继续请求
    // 返回false：请求失败
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        System.out.println("正在拦截【" + requestURI + "】页面");

        // 获取HttpSession会话对象
        HttpSession session = request.getSession();

        // 获取登录者信息
        User user = (User) session.getAttribute("user");

        if (user == null){
            System.out.println("拦截器正在试图使用cookie自动登录");

            // 获取cookies
            Cookie[] cookies = request.getCookies();

            // cookies如果为空直接登录失败
            if (cookies == null){
                response.sendRedirect("/static/login.html");
                return false;
            }

            String loginAct = "";
            String loginPwd = "";

            for (Cookie cookie : cookies) {
                if ("loginAct".equals(cookie.getName())){
                    loginAct = cookie.getValue();
                }else if ("loginPwd".equals(cookie.getName())){
                    loginPwd = cookie.getValue();
                }
            }

            // 调用业务查看用户是否存在
            User userTemp = userServices.login(loginAct, loginPwd);

            if (userTemp == null){
                response.sendRedirect("/static/login.html");
                return false;
            }else {
                // 自动登录成功，则把用户数据放到Session里面
                session.setAttribute("user", userTemp);
                return true;
            }

        }else {
            return true;
        }
    }

    // 响应之后，但是没有到界面【或者浏览器】
    // 响应之后，【视图解析器解析之前】
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 响应结束
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
